import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'

import viteCompression from 'vite-plugin-compression'
// eslint
import eslintPlugin from 'vite-plugin-eslint'

import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import legacy from '@vitejs/plugin-legacy'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    legacy({
      // 兼容浏览器列表
      targets: ['Android >= 7', 'chrome >= 51', 'firefox >= 54', 'ios >= 10']
    }),
    vue(),
    AutoImport({
      imports: [
        'vue',
        'vue-router'
      ],
      dirs: [
        'src/utils/**',
        'src/stores/**'
      ],
      dts: 'src/auto-import/imports.d.ts',
      eslintrc: {
        enabled: true
      },
      resolvers: [
        ElementPlusResolver(),
        // 自动导入图标组件
        IconsResolver({
          prefix: 'Icon'
        })
      ]
    }),
    Components({
      dirs: [
        'src/components'
      ],
      dts: 'src/auto-import/components.d.ts',
      resolvers: [
        ElementPlusResolver(),
        // 自动注册图标组件
        IconsResolver({
          enabledCollections: ['ep']
        })
      ]
    }),
    Icons({
      autoInstall: true
    }),
    // eslint
    eslintPlugin({
      include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue']
    }),
    // 对大于 1k 的文件进行压缩
    viteCompression({
      threshold: 1000
    }),
    ElementPlus()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
    }
  },
  server: {
    host: '0.0.0.0',
    port: 3344,
    open: true
  },
  build: {
    base: './',
    rollupOptions: {
      // 静态资源分类打包
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        // 静态资源分拆打包
        manualChunks (id) {
          if (id.includes('node_modules')) {
            if (id.toString().indexOf('.pnpm/') !== -1) {
              return id.toString().split('.pnpm/')[1].split('/')[0].toString()
            } else if (id.toString().indexOf('node_modules/') !== -1) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      }
    },
    sourcemap: false,
    minify: 'terser',
    reportCompressedSize: false
  }
})
